package com.sit.estatemanagementserver.service;

import com.alibaba.fastjson2.JSONObject;
import com.sit.estatemanagementserver.dao.VisitInfoDao;
// 假设 VisitorDao 存在
// import com.sit.estatemanagementserver.dao.VisitorDao;
import com.sit.estatemanagementserver.enity.VisitInfo;
// import com.sit.estatemanagementserver.enity.Visitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashSet;
import java.util.List;

@Service
public class VisitorService {

    @Autowired
    private VisitInfoDao visitInfoDao;

    @Autowired
    private SignatureService signatureService;

    @Value("${server.base-url}")
    private String serverBaseUrl;

    public Boolean addVisitInfo(VisitInfo visitInfo) {
        // 1. 创建包含核心信息和时间窗口的JSON数据包
        JSONObject payloadJson = new JSONObject();
        payloadJson.put("visitorName", visitInfo.getVisitorName());
        payloadJson.put("visitingRoomNumber", visitInfo.getVisitingRoomNumber());

        // 核心修改：同时添加exp和nbf两个时间戳
        LocalDateTime startTime = visitInfo.getVisitStartTime();
        LocalDateTime endTime = visitInfo.getVisitEndTime();

        long notBeforeTime = startTime.toEpochSecond(ZoneOffset.UTC); // 生效时间戳
        long expirationTime = endTime.toEpochSecond(ZoneOffset.UTC);  // 过期时间戳

        payloadJson.put("nbf", notBeforeTime); // Not Before
        payloadJson.put("exp", expirationTime); // Expiration Time

        String jsonData = payloadJson.toJSONString();

        // --- 后续的签名和URL生成逻辑保持不变 ---

        String base64JsonData = Base64.getUrlEncoder().withoutPadding().encodeToString(jsonData.getBytes(StandardCharsets.UTF_8));
        String signature = signatureService.sign(jsonData);
        String urlSafeSignature = signature.replace('+', '-').replace('/', '_');

        String finalUrl = serverBaseUrl + "/visitor/verify"
                + "?data=" + base64JsonData
                + "&sig=" + urlSafeSignature;

        visitInfo.setQrCodePayload(finalUrl);
        return visitInfoDao.addVisitInfo(visitInfo);
    }

    // 查询访客信息
    public List<VisitInfo> getVisitInfoByRoomNumber(String roomNumber) {
        // 重构: getVisitInfosByRoom 已经在DAO层实现
        return visitInfoDao.getVisitInfosByRoom(roomNumber);
    }
}